<template>
  <div class="page-main" v-title data-title="成品信息明细">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">成品信息明细</span>
        <div class="btn-line">
          <a-button class="hte-btn add-btn" type="primary" :loading="btnLoading" @click="doSave">保存</a-button>          
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" >
          <section>
            <div class="section-header">基础信息</div>
            <template>        
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="品种编号" prop="prodNo">                    
                    <a-input v-model="form.prodNo" placeholder="请输入" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="品种名称" prop="prodName"> 
                    <a-input v-model="form.prodName" placeholder="请输入" allowClear/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="品种类型" prop="prodType">
                    <a-select v-model="form.prodType" placeholder="请选择" allowClear>
                      <a-select-option
                        v-for="(item) in dict.prodTypeList"
                        :key="'prodType' + item.code"
                        :value="item.code"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="品种大类" prop="prodClass">
                    <a-select v-model="form.prodClass" placeholder="请选择" allowClear>
                      <a-select-option
                        v-for="(item) in dict.prodClassList"
                        :key="'prodClass' + item.code"
                        :value="item.code"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="固形物大小" prop="solidSize">    
                    <a-input-number v-model="form.solidSize" placeholder="请输入" allowClear style="width:100%"/>               
                  </a-form-model-item>                  
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="创建人/创建时间">
                    <a-input v-model="form.createInfo" placeholder="自动生成" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="有机产品">
                    <a-switch checked-children="是" un-checked-children="否"  v-model="form.organic" />
                  </a-form-model-item>
                </a-col>  
                <a-col :span="8">
                  <a-form-model-item label="低防腐剂">
                    <a-switch checked-children="是" un-checked-children="否"  v-model="form.antiseptic" />
                  </a-form-model-item>
                </a-col>  
                <a-col :span="8">
                  <a-form-model-item label="特殊感官">
                    <a-switch checked-children="是" un-checked-children="否"  v-model="form.specialSense" />
                  </a-form-model-item>
                </a-col>  
              </a-row> 
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="盐分大小" prop="saltSize">    
                    <a-input-number v-model="form.saltSize" placeholder="请输入" allowClear style="width:100%"/>               
                  </a-form-model-item>                  
                </a-col>   
               </a-row>       
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="备注">
                    <a-textarea
                      allowClear
                      v-model="form.remark"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                      style="width: 100%"
                      :maxLength="300"
                      placeholder="请输入（300个字符以内）"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>            
            </template>                     
          </section>
        </a-form-model>
        <section>                
          <div class="section-header mt15">
            <div>配料表</div>
            <div class="btn-line">
              <a-button class="hte-btn add-btn" type="primary" :loading="btnLoading" @click="handAction('add')">插入</a-button>
              <a-button class="hte-btn" :loading="btnLoading" @click="visible=true">导入</a-button>          
              <a-button class="hte-btn" type="danger" :loading="btnLoading" @click="handAction('del')">删除</a-button>
            </div>
          </div>
          <div class="section-table">
            <div>
              <a-table
                class="hte-table-content"
                :columns="fileColumns"
                :data-source="fileData"
                :pagination="false"
                :loading="tabLoading"
                :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                :rowKey="(record,index)=>{return index+record.materialNoStr}"                
                bordered
                size="middle"
              >
                <template slot="swicth" slot-scope="text">
                  <span>{{ text ? '是' : '否' }}</span>
                </template>
                <template slot="materialNo" slot-scope="text, record, index">
                  <a-select
                    show-search
                    placeholder="请选择"
                    v-model="record.materialNoStr"
                    optionLabelProp="value"
                    @change="(e) => handleChange(e, record, index)"
                    >
                    <a-select-option v-for="(item) in matOptions"
                        :key="index +'-'+ item.materialNoStr "
                        :value="item.materialNoStr">
                      {{ item.materialNoStr + '--' +item.materialName}}
                    </a-select-option>
                  </a-select>
                </template>
              </a-table>
            </div>
          </div>        
        </section> 
      </div>
    </div>
    <template>
      <a-modal
        v-model="visible"
        width="50vw"
        :bodyStyle="{ padding: '10px 40px 10px 20px' }"
        title="导入配料表"
        :confirmLoading="loading"    
        @ok="handleOk"
        @cancel="handleCancel"
      >      
        <div>
          <a-form-model ref="ruleVisiForm" :model="dataVisiForm" :rules="rulesVisible" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">           
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="配料编码" prop="materialNo">
                  <a-textarea
                    v-model="dataVisiForm.materialNo"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    style="width: 100%"
                    :maxLength="500"
                    allowClear
                    placeholder="输入多个请用英文,隔开，不留空格"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-modal> 
    </template>
  </div>
</template>
<script>
import {getAction, postAction } from '@/api/manage';
import Vue from 'vue';
import { ClearLibMixin } from '@/mixins/ClearLibMixin'
import {codeInfoList} from '@/api/codeInfo'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  mixins: [ClearLibMixin],
  data() {
    return { 
           
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'FinishedInfo',
      },
      id:this.$route.query.id,      
      form: {},
      rules: {
        prodNo: [{ required: true, message: '请输入品种编号', trigger: 'blur' },],
        prodName: [{ required: true, message: '请输入品种名称', trigger: 'blur' },],
        prodType: [{ required: true, message: '请选择品种类型', trigger: 'change' },],
        prodClass: [{ required: true, message: '请选择品种大类', trigger: 'change' },],
        solidSize: [{ required: true, message: '请输入固形物大小', trigger: 'blur' },],
        saltSize: [{ required: true, message: '请输入盐分大小', trigger: 'blur' },],
      },
      btnLoading:false,
      url: {
        codeInfoList:'/manage/codeInfo/queryByType',
        matList:'/hteWashMaterial/list',
        matImport:'/hteWashMaterial/matImport',
        save:'/hteWashProduct/save',
        queryById:'/hteWashProduct/info/'
      },
      prodTypeList: [],
      prodClassList: [],
      matOptions:[],
      // 配料表
      fileColumns: [
        {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:50,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          },
          isImportExcelColumns:false
        },        
        { title: '配料编号',dataIndex: 'materialNo',align: 'center',scopedSlots: { customRender: 'materialNo' },},
        { title: '配料名称', dataIndex: 'materialName',  align: 'center' },
        { title: '过敏原', dataIndex: 'allergy',  align: 'center', scopedSlots: { customRender: 'swicth' }, },
        { title: '过敏原分类', dataIndex: 'allergyLevel',  align: 'center',
          customRender: (text, record) => {
            if (text == 1) {
              return 'A类';
            } else if (text == 2) {
              return 'B类';
            } else if (text == 3) {
              return 'C类';
            } else if (text == 4) {
              return 'D类';
            }
            return text;
          }
        },
        { title: '配料分组', dataIndex: 'materialGroupName',align: 'center'},
        { title: '特殊气味', dataIndex: 'smell', align: 'center', scopedSlots: { customRender: 'swicth' }, },
        { title: '备注', dataIndex: 'remark', align: 'center' },
      ],
      fileData: [], 
      selectedRowKeys: [],
      selectionRows: [],
      tabLoading: false,
      dictList: [],
      // 导入
      visible: false,
      rulesVisible: {
        materialNo: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      dataVisiForm: {},
      loading: false,
      dict:{
        prodTypeList: [],
        prodClassList: [],
      },
    }
  },
  computed:{
  },
  mounted() {
    if(this.id){
      this.initOrder(this.id); // 修改
    }else{
      // this.form.applyUserId=this.userinfo.info.username;
      // this.form.applyUserName=this.userinfo.info.realname;
      // this.form.applyDeptId=this.userinfo.info.deptId;
      // this.form.applyDeptName=this.userinfo.info.deptName;
      // this.form.applyInfo=this.form.applyUserName+'/'+this.form.applyDeptName;
    }
    this.initDict(); //配料编号字典
  },
  methods: {
    initOrder(){
      getAction(this.url.queryById + this.id).then((res) => {
        if (res.code == 200) {
          this.form=res.result;
          if(res.result.prodMatList){
            this.fileData = res.result.prodMatList
          }
          this.form.createInfo=this.form.createUserName+'/'+this.form.createTime;          
          this.form.prodType = this.form.prodType + '';
          this.form.prodClass = this.form.prodClass + ''; 
        } else {
          this.$message.warning('查询失败:' + res.message)
        }
      })
    },
    initDict(){
     const list = [{name:'prodTypeList',type:`${this.washType}wash_product_type`},{name:'prodClassList',type:`${this.washType}wash_product_class`} ]
      list.forEach((item, index)=>{
        codeInfoList({type:item.type,pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict[item.name] = res.result.records
           
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
      })  
      getAction(this.url.matList,{washType:this.washType})
        .then((res) => {
          if (res.code == 200) {
            this.matOptions = res.result
          } else {
            this.$message.warning('查询配料表失败:' + res.message)
          }
      })
    },
    /**
     * 配料表
     */
    async handleChange(e, record, index){      
      debugger 
      const flag = this.fileData.some(item => {
        return item.materialNoStr == e && item.materialName
      })
      if (flag) {
        this.$message.warning(`该配料编号${e}已存在`)
        this.fileData.splice(index, 1);
        return;      
      }
      const mat = this.matOptions.find(it=>it.materialNoStr == e);
      this.fileData[index] = mat;
      // this.$set(this.fileData[index], 'materialName', mat.materialName)
      // this.$set(this.fileData[index], 'allergy', mat.allergy)
      this.$forceUpdate();
    },
    
    /**
     * 保存
     */
    async doSave(){   
      let flag = false
      try{
        flag = await this.$refs.ruleForm.validate();
      }catch(e){
        flag = false;
      }
      if(!flag){
        return ;
      }
      if(!this.fileData.length){
        this.$message.warning('请先选择至少一份配料！')
        return
      }
      const flag2 = this.fileData.some(item=>{
        return !item.materialNoStr
      })      
      if(flag2){
        this.$message.warning('请先完成配料配置！')
        return
      }
      const array = this.fileData.map(item=>{
        return item.materialNoStr
      })
      if(new Set(array).size !== this.fileData.length){
        this.$message.warning('配料表存在重复配料编号！')
        return
      }
      if(flag){
        console.log(this.fileData, this.form)
      }
      // this.form.prodMatList = this.fileData.map(item=>{
      //   return {materialId:item.id}
      // });
      this.form.prodMatList = this.fileData;
      this.form.washType = this.washType
      postAction(this.url.save, this.form).then(res => {
        if (res.success) {
          this.$emit('ok')
          this.handleCancel()
          this.$message.success('保存成功')
          this.form.id= res.result.id;
        } else {
          this.$message.error('操作失败:' + res.message)
        }
      })  
    },  
    handAction(type){     
      switch (type) {
        case 'del':
          // 删除，可多选
          const that = this
          if (this.selectedRowKeys.length == 0) {
            this.$message.warning('请选择至少一条数据！')
            return
          }
          this.$confirm({
            title: '确认删除',
            content: '请确认是否删除此配料?',
            onOk: function () {
              that.selectionRows.forEach(row => {              
                const index = that.fileData.findIndex(v => v.id === row.id);
                if(index != -1){
                  that.fileData.splice(index, 1);  
                }              
              });
              that.selectionRows = [];
              that.selectedRowKeys = [];
            },
          })
          break
        case 'add':
          // 插入
          this.selectedRowKeys = []
          this.selectionRows = []
          this.fileData.push({key: this.fileData.length + 1})
          break
        default:
          break
      }    
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    /**
     * 导入配料表 
     */
    handleCancel(){
      this.visible = false
      this.dataVisiForm = {}
      // this.$refs.ruleVisiForm.resetFields()
    },
    async handleOk(){
      const that = this;
      const flag = await this.$refs.ruleVisiForm.validate()
      if(flag){
        this.loading = true
        getAction(this.url.matImport, {washType:this.washType, materialNos:this.dataVisiForm.materialNo}).then((res) => {
          if (res.code == 200) {
            if(res.result){
              that.fileData.push(...res.result);
              that.handleCancel()
            }
          } else {
            this.$message.warning(res.message)
          }
          that.loading = false
        })
      }else{
        this.loading = false
      }      
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
/deep/ .ant-select {
  width:100% !important;
}
</style>
